<?php

namespace app\company\service;

use app\company\model\CompanyModel;
use app\model\UserModel;
use app\service\BaseLoginService;
use think\db\exception\DbException;

class CompanyLoginService extends BaseLoginService
{
    public string $loginType = 'company';

    /**
     * 登录
     * @param array $params
     * @return bool
     * @throws DbException
     */
    public function login(array $params): bool
    {
        $field = 'id,username,realname,mobile,avatar,status,role_id';

        //登录判断
        $user = UserModel::where('username|mobile', $params['username'])
            ->where('password', $params['password'])
            ->field($field)
            ->find();
        if(!$user){
            return false;
        }

        //判断是否公司管理员
        $company = CompanyModel::where([
                'admin_user' => $user->username,
                'status' => 1,
            ])
            ->find();
        if(!$company){
            return false;
        }

        //更新登录时间
        $user->save([
            'login_time' => time()
        ]);

        $this->jwtData = [
            'id' => $user->id,
            'name' => $user->realname,
            'role' => $user->role_id,
            'login_type' => $this->loginType,
            'cid' => $company->id
        ];

        $this->userInfo = $user->toArray();
        $this->success = true;

        //用户信息中追加公司信息
        $this->userInfo['company_name'] = $company->name;
        $this->userInfo['role_name'] = '公司管理员';
        $this->userInfo['cid'] = $company->id;
        $this->userInfo['login_type'] = $this->loginType;

        return true;
    }

}